package cn.com.kh;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.json.JSONObject;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class KHUtil {
    private static final Log log = LogFactory.getLog(KHUtil.class);

    public static void main(String[] args) {
        // TODO Auto-generated method stub

    }

    // 将字符串使用sha1加密返回加密字符串(realme)
    public static String getsh1(String inString) {
        if (StringUtils.isEmpty(inString)) {
            return null;
        } else {
            return DigestUtils.shaHex(inString);
        }
    }

    // 将字符串使用base64加密返回加密字符串(realme)
    public static String getbase64(String inString) {

        if (StringUtils.isEmpty(inString)) {
            return null;
        } else {
            try {
                return Base64.getEncoder().encodeToString(inString.getBytes("utf-8"));
            } catch (Exception e) {
                log.warn("将字符串使用base64加密异常:" + e.getMessage());
                return null;
            }
        }
    }

    // 生成指定位数的随机字符串
    public static String getRandomString(int length) {
        String str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        Random random = new Random();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < length; i++) {
            int number = random.nextInt(62);
            sb.append(str.charAt(number));
        }
        return sb.toString();
    }

    // 生成指随机正整数串
    public static String getIntRandom(int len) {
        //生成六位随机正整数
        Random random = new Random();
        String verificationCode = String.valueOf(random.nextInt(9) + 1);
        for (int i = 0; i < len - 1; i++) {
            verificationCode += random.nextInt(10);
        }
        return verificationCode;
    }

    // 非空校验isNull
    public static boolean isNull(String value) {

        boolean reFlag = true;
        if (value == null || value.length() <= 0) {
            reFlag = true;
        } else {
            reFlag = false;
        }

        return reFlag;
    }

    // 非空校验isNullMSG
    public static String isNullMSG(String key, String value) {

        String reResult = "";
        if (value == null || value.length() <= 0) {
            reResult = key + "必填字段;";
        }
        return reResult;
    }

    // List To String[]
    public static String[] listToStringArr(List<String> inList) {
        String[] strArray = inList.toArray(new String[inList.size()]);
        return strArray;
    }

    // 解析Json值(此方法增加需要解析的key不存在保护)
    public static String GetJV(JSONObject inJson, String getKey) {
        String Rev_Value = null;
        try {
            Rev_Value = inJson.getString(getKey);
        } catch (Exception e) {
            try {
                Rev_Value = String.valueOf(inJson.getLong(getKey));
            } catch (Exception e11) {
                try {
                    Rev_Value = String.valueOf(inJson.getInt(getKey));
                } catch (Exception e1) {
                    try {
                        Rev_Value = String.valueOf(inJson.getJSONArray(getKey));
                    } catch (Exception e2) {
                        try {
                            Rev_Value = String.valueOf(inJson.getJSONObject(getKey));
                        } catch (Exception e3) {
                            Rev_Value = "";
                        }
                    }
                }
            }
        } finally {
            if (Rev_Value == null || Rev_Value.equals("null") || Rev_Value.length() <= 0) {
                Rev_Value = "";
            } else {
                log.debug("GetJV:" + Rev_Value);
            }
        }
        return Rev_Value;
    }

    // 解析获取String[]值
    public static String getStringV(String stringInfo, String key) {

        String reValue = "";
        String[] xArr = stringInfo.split("&");
        int xLen = xArr.length;
        for (int i = 0; i < xLen; i++) {
            String yInfo = xArr[i];
            String[] yArr = yInfo.split("=");
            try {
                if (yArr[0].equals(key)) {
                    try {
                        reValue = yArr[1];
                    } catch (Exception e) {
                        reValue = "";
                        log.debug("异常value:" + yArr.toString());
                    }
                }
            } catch (Exception e) {
                log.warn("异常key=value片段:" + yArr.toString());
            }
        }

        return reValue;

    }

    // MD5加密
    public static String getMD5(String plainText) {
        StringBuffer buf = new StringBuffer("");
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(plainText.getBytes());
            byte b[] = md.digest();
            int i;

            for (int offset = 0; offset < b.length; offset++) {
                i = b[offset];
                if (i < 0)
                    i += 256;
                if (i < 16)
                    buf.append("0");
                buf.append(Integer.toHexString(i));
            }
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return buf.toString();
    }

    /*
     * 将时间字符串转换为时间戳
     */
    static String dateToStamp(String s) {
        String res;
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
        Date date = null;
        try {
            date = simpleDateFormat.parse(s);
        } catch (Exception e) {
            log.error("dateToStamp Exception:" + e.getMessage());
        }

        long ts = date.getTime();
        res = String.valueOf(ts);
        return res;
    }

    /*
     * 将时间戳转换为时间字符串
     */
    static String stampToDate(String s) {
        String res;
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
        long lt = new Long(s);
        Date date = new Date(lt);
        res = simpleDateFormat.format(date);
        return res;
    }

    // 是否内部IP调用
    public static Object getRemoteHost(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if ((ip == null) || (ip.length() == 0) || ("unknown".equalsIgnoreCase(ip))) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if ((ip == null) || (ip.length() == 0) || ("unknown".equalsIgnoreCase(ip))) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if ((ip == null) || (ip.length() == 0) || ("unknown".equalsIgnoreCase(ip))) {
            ip = request.getRemoteAddr();
        }
        String serverName = request.getServerName();
        log.debug("serverName:" + serverName + " ip:" + ip);

        if (("localhost".equals(serverName)) || ("127.0.0.1".equals(serverName)) || ("127.0.0.1".equals(ip)) || ("0:0:0:0:0:0:0:1".equals(ip))) {
            return true;
        }
        return false;
    }

    // 将Map转为x-www-form-urlencoded
    public static String urlencode(Object params, String key) {
        String res = "";
        if (params instanceof Map) {
            Map<String, Object> _params = (Map<String, Object>) params;
            for (String i : _params.keySet()) {
                String k = key.isEmpty() ? i : (key + "[" + i + "]");
                String encodeValue = urlencode(_params.get(i), k);
                if (!encodeValue.isEmpty()) {
                    res += '&' + encodeValue;
                }
            }
        } else if (params instanceof List) {
            List<Object> _params = (List<Object>) params;
            for (Integer i = 0; i < _params.size(); i++) {
                String k = key.isEmpty() ? i.toString() : (key + "[" + i.toString() + "]");
                String encodeValue = urlencode(_params.get(i), k);
                if (!encodeValue.isEmpty()) {
                    res += '&' + encodeValue;
                }
            }
        } else if (params.getClass().isArray()) {
            Object[] _params;
            if (params instanceof Object[]) {
                _params = (Object[]) params;
            } else if (params instanceof String[]) {
                _params = (String[]) params;
            } else if (params instanceof int[]) {
                _params = ArrayUtils.toObject((int[]) params);
            } else if (params instanceof double[]) {
                _params = ArrayUtils.toObject((double[]) params);
            } else {
                _params = new Object[]{};
            }
            for (Integer i = 0; i < _params.length; i++) {
                String k = key.isEmpty() ? i.toString() : (key + "[" + i.toString() + "]");
                String encodeValue = urlencode(_params[i], k);
                if (!encodeValue.isEmpty()) {
                    res += '&' + encodeValue;
                }
            }
        } else if (params instanceof String) {
            String _params = (String) params;
            try {
                res += '&' + URLEncoder.encode(key, "UTF-8") + '=' + URLEncoder.encode(_params, "UTF-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        } else if (params instanceof Number) {
            Number _params = (Number) params;
            try {
                res += '&' + URLEncoder.encode(key, "UTF-8") + '=' + URLEncoder.encode(_params.toString(), "UTF-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        } else {
            return "";
        }
        return res.substring(1);
    }

    // FastJson Null的问题
    public static String FastJsonNull(String value) {

        if (value == null) {
            return "";
        } else {
            return value;
        }
    }

    /**
     * 是否含有sql注入，返回true表示含有
     * @param obj
     * @return
     */
    public static boolean containsSqlInjection(Object obj){
        Pattern pattern= Pattern.compile("(.*\\=.*\\-\\-.*)|(.*(\\+|\\-).*)|(.*\\w+(%|\\$|#|&)\\w+.*)|(.*\\|\\|.*)|(.*\\s+(and|or)\\s+.*)|(.*\\b(select|update|union|and|or|delete|insert|trancate|char|into|substr|ascii|declare|exec|count|master|into|drop|execute)\\b.*)");
        Matcher matcher=pattern.matcher(obj.toString().toLowerCase());
        return matcher.find();
    }

    public static boolean objIsNull(Object obj){

        boolean reFlag = true;
        if (obj == null ) {
            reFlag = true;
        } else {
            reFlag = false;
        }

        return reFlag;
    }

    public static String getNameWithoutSuffix(String filename)
    {
        try
        {
            if ((filename != null) && (filename.length() > 0)) {
                int dot = filename.lastIndexOf(".");
                if ((dot > -1) && (dot < filename.length()))
                    return filename.substring(0, dot);
            }
        }
        catch (Exception e) {
            log.error(e);
        }
        return filename;
    }



    // 解析Json值(此方法增加需要解析的key不存在保护)
    public static String GetSFJV(net.sf.json.JSONObject inJson, String getKey) {
        String Rev_Value = null;
        try {
            Rev_Value = inJson.getString(getKey);
        } catch (Exception e) {
            try {
                Rev_Value = String.valueOf(inJson.getLong(getKey));
            } catch (Exception e11) {
                try {
                    Rev_Value = String.valueOf(inJson.getInt(getKey));
                } catch (Exception e1) {
                    try {
                        Rev_Value = String.valueOf(inJson.getJSONArray(getKey));
                    } catch (Exception e2) {
                        try {
                            Rev_Value = String.valueOf(inJson.getJSONObject(getKey));
                        } catch (Exception e3) {
                            Rev_Value = "";
                        }
                    }
                }
            }
        } finally {
            if (Rev_Value == null || Rev_Value.equals("null") || Rev_Value.length() <= 0) {
                Rev_Value = "";
            } else {
                log.debug("GetJV:" + Rev_Value);
            }
        }
        return Rev_Value;
    }

}
